package com.example.wuqiu.config.tcp;

import com.example.wuqiu.module.sys.entity.SysWebsocket;
import com.example.wuqiu.module.sys.service.SysWebsocketService;
import com.example.wuqiu.utils.IdHelp;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Slf4j
public class TcpServerHandler extends SimpleChannelInboundHandler<String> {
    private final Map<String, ChannelHandlerContext> clientChannels;

    private SysWebsocketService websocketService;

    public TcpServerHandler(Map<String, ChannelHandlerContext> clientChannels, SysWebsocketService websocketService) {
        this.clientChannels = clientChannels;
        this.websocketService = websocketService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("客户端连接：" + ctx.channel().remoteAddress());
        ctx.writeAndFlush("连接成功！\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        // 如果消息以 "ID:" 开头，表示客户端发送了用户ID
        if (msg.startsWith("ID:")) {
            // 提取用户ID
            String userId = msg.substring(3);
            // 将用户ID与ChannelHandlerContext关联
            userId = userId.replaceAll("\n", "");
            clientChannels.put(userId, ctx);
            System.out.println("客户端 " + ctx.channel().remoteAddress() + " 注册用户ID: " + userId);
            ctx.writeAndFlush("注册成功！你的用户ID是: " + userId + "\n");
        } else if (msg.startsWith("PING")) {
            return;
        }else{
            try {
                log.info("通讯消息" + msg);
                // 创建 Gson 实例
                Gson gson = new GsonBuilder()
                        // 指定日期格式
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")
                        .create();
                // 将 JSON 字符串转换为 SysWebsocket 对象
                SysWebsocket sysWebsocket = gson.fromJson(msg, SysWebsocket.class);

                ChannelHandlerContext channelHandlerContext = clientChannels.get(sysWebsocket.getReceiveId());
                if (channelHandlerContext != null) {
                    channelHandlerContext.writeAndFlush(msg);
                }else {
                    sysWebsocket.setId(IdHelp.UUID());
                    sysWebsocket.setSendDate(new Date());
                    websocketService.save(sysWebsocket);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.info("其他消息" + msg);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        // 客户端断开连接时，从映射中移除
        clientChannels.values().removeIf(context -> context.equals(ctx));
        log.info("客户端断开连接：" + ctx.channel().remoteAddress());
    }
}
